#!/bin/bash

# 图片上传功能修复脚本
echo "🖼️  修复图片上传功能..."

PROJECT_DIR="/var/www/web-notes"
WEB_ROOT="/var/www/html"
BACKEND_DIR="/var/www/web-notes/web-notes-backend"

echo "📁 检查和创建上传目录..."
sudo mkdir -p $BACKEND_DIR/uploads/images
sudo chown -R www-data:www-data $BACKEND_DIR/uploads/
sudo chmod -R 755 $BACKEND_DIR/uploads/

echo "📝 检查目录权限:"
ls -la $BACKEND_DIR/uploads/

cd $PROJECT_DIR

echo ""
echo "🎨 重新构建前端（包含上传修复）..."
cd web-notes-frontend
npm run build

echo ""
echo "📤 重新部署前端文件..."
sudo rm -rf $WEB_ROOT/*
sudo cp -r dist/* $WEB_ROOT/
sudo chown -R www-data:www-data $WEB_ROOT/
sudo chmod -R 755 $WEB_ROOT/

echo ""
echo "🔄 重启后端服务..."
pm2 restart web-notes-api || echo "后端服务未运行，将启动新实例"
cd $BACKEND_DIR
pm2 start dist/index.js --name "web-notes-api" || echo "服务已存在"

echo ""
echo "⏳ 等待服务启动..."
sleep 3

echo ""
echo "🧪 测试上传功能..."

# 测试上传目录访问
echo "测试上传目录访问:"
if [ -d "$BACKEND_DIR/uploads/images" ]; then
    echo "✅ 上传目录存在"
    echo "目录权限: $(ls -ld $BACKEND_DIR/uploads/images)"
else
    echo "❌ 上传目录不存在"
fi

# 测试 Nginx 配置
echo ""
echo "测试 Nginx 上传路径配置:"
if curl -s -I http://localhost/uploads/ | grep -q "200\|403\|404"; then
    echo "✅ Nginx 上传路径配置正常"
else
    echo "❌ Nginx 上传路径配置有问题"
fi

# 测试后端上传API
echo ""
echo "测试后端上传API端点:"
if curl -s http://localhost:3000/api/upload/image -X POST | grep -q "没有上传文件\|success\|error"; then
    echo "✅ 后端上传API响应正常"
else
    echo "❌ 后端上传API无响应"
fi

echo ""
echo "🔍 检查常见问题:"

# 检查磁盘空间
echo "磁盘空间:"
df -h | grep -E "(/$|/var)"

# 检查 PM2 状态
echo ""
echo "PM2 服务状态:"
pm2 list | grep web-notes-api

echo ""
echo "✅ 图片上传修复完成！"
echo ""
echo "🧪 测试步骤:"
echo "1. 刷新浏览器页面"
echo "2. 在笔记编辑器中尝试上传图片"
echo "3. 如果还有问题，检查浏览器控制台的错误信息"
echo ""
echo "📋 如果仍有问题，请检查:"
echo "- 浏览器开发者工具的 Network 选项卡"
echo "- PM2 日志: pm2 logs web-notes-api"
echo "- Nginx 错误日志: tail -f /var/log/nginx/web-notes-error.log"